package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.mapper.DepartmentMapper;
import com.woniuxy.mapper.DoctorMapper;
import com.woniuxy.mapper.HospitalMapper;
import com.woniuxy.pojo.Department;
import com.woniuxy.pojo.Doctor;
import com.woniuxy.pojo.Hospital;
import com.woniuxy.pojo.dto.SearchDoctorDTO;
import com.woniuxy.pojo.vo.DoctorVO;
import com.woniuxy.service.DoctorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
        implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private HospitalMapper hospitalMapper;

    @Override
    public Page<DoctorVO> getDoctors(Integer pageNum, Integer pageSize) {
        // 1. 创建分页对象
        Page<Doctor> page = new Page<>(pageNum, pageSize);

        // 2. 查询医生分页数据
        Page<Doctor> doctorPage = doctorMapper.selectPage(page, new QueryWrapper<Doctor>()
                .orderByDesc("create_time"));

        List<Doctor> doctors = doctorPage.getRecords();

        // 3. 如果没有数据，直接返回空分页
        if (doctors.isEmpty()) {
            return new Page<>(pageNum, pageSize);
        }

        // 4. 收集关联ID
        List<Integer> deptIds = doctors.stream()
                .map(Doctor::getDepartmentId)
                .distinct()
                .collect(Collectors.toList());

        List<Integer> hospIds = doctors.stream()
                .map(Doctor::getHospitalId)
                .distinct()
                .collect(Collectors.toList());

        // 5. 批量查询关联数据
        Map<Integer, Department> deptMap = departmentMapper.selectBatchIds(deptIds)
                .stream()
                .collect(Collectors.toMap(Department::getId, dept -> dept));

        Map<Integer, Hospital> hospMap = hospitalMapper.selectBatchIds(hospIds)
                .stream()
                .collect(Collectors.toMap(Hospital::getId, hosp -> hosp));

        // 6. 组装VO
        List<DoctorVO> voList = new ArrayList<>();
        for (Doctor doctor : doctors) {
            DoctorVO vo = new DoctorVO();
            BeanUtils.copyProperties(doctor, vo);

            // 设置科室信息
            Department dept = deptMap.get(doctor.getDepartmentId());
            if (dept != null) {
                vo.setDepartmentName(dept.getName());
                vo.setDepartmentLevel(dept.getLevel());
            }

            // 设置医院信息
            Hospital hosp = hospMap.get(doctor.getHospitalId());
            if (hosp != null) {
                vo.setHospitalName(hosp.getName());
                vo.setHospitalAddress(hosp.getAddress());
            }

            voList.add(vo);
        }

        // 7. 创建返回的分页对象
        Page<DoctorVO> resultPage = new Page<>(pageNum, pageSize);
        resultPage.setRecords(voList);
        resultPage.setTotal(doctorPage.getTotal());
        resultPage.setPages(doctorPage.getPages());

        return resultPage;
    }

    @Override
    public List<String> getDartment() {
        // 1. 创建查询条件：level = 1 (一级科室) 且 parent_id IS NULL
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("level", 1)
                .isNull("parent_id")
                .select("DISTINCT name"); // 去重查询科室名称

        // 2. 执行查询
        List<Department> departments = departmentMapper.selectList(wrapper);

        // 3. 提取科室名称
        return departments.stream()
                .map(Department::getName)
                .collect(Collectors.toList());
    }

    @Override
    public Page<DoctorVO> searchDoctor(SearchDoctorDTO queryDTO, Integer pageNum, Integer pageSize) {
        Page<Doctor> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(queryDTO.getDoctorName()), "name", queryDTO.getDoctorName())
                .like(StringUtils.isNotBlank(queryDTO.getHospitalName()), "hospital_name", queryDTO.getHospitalName())
                .eq(queryDTO.getFirstLevelDeptId() != null, "first_level_dept_id", queryDTO.getFirstLevelDeptId())
                .eq(queryDTO.getStatus() != null, "status", queryDTO.getStatus())
                .between(queryDTO.getBeginCreateTime() != null && queryDTO.getEndCreateTime() != null,
                        "create_time", queryDTO.getBeginCreateTime(), queryDTO.getEndCreateTime())
                .orderByDesc("create_time");
        Page<Doctor> doctorPage = doctorMapper.selectPage(page, wrapper);
        List<Doctor> doctors = doctorPage.getRecords();
        if (doctors.isEmpty()) {
            return new Page<>(pageNum, pageSize);
        }
        List<Integer> deptIds = doctors.stream()
                .map(Doctor::getDepartmentId)
                .distinct()
                .collect(Collectors.toList());
        List<Integer> hospIds = doctors.stream()
                .map(Doctor::getHospitalId)
                .distinct()
                .collect(Collectors.toList());
        Map<Integer, Department> deptMap = departmentMapper.selectBatchIds(deptIds)
                .stream()
                .collect(Collectors.toMap(Department::getId, dept -> dept));
        Map<Integer, Hospital> hospMap = hospitalMapper.selectBatchIds(hospIds)
                .stream()
                .collect(Collectors.toMap(Hospital::getId, hosp -> hosp));
        List<DoctorVO> voList = new ArrayList<>();
        for (Doctor doctor : doctors) {
            DoctorVO vo = new DoctorVO();
            BeanUtils.copyProperties(doctor, vo);
            Department dept = deptMap.get(doctor.getDepartmentId());
            if (dept != null) {
                vo.setDepartmentName(dept.getName());
                vo.setDepartmentLevel(dept.getLevel());
                vo.setHospitalName(hospMap.get(doctor.getHospitalId()).getName());
                vo.setHospitalAddress(hospMap.get(doctor.getHospitalId()).getAddress());

            }
            voList.add(vo);
            Page<DoctorVO> resultPage = new Page<>(pageNum, pageSize);
            resultPage.setRecords(voList);
            resultPage.setTotal(doctorPage.getTotal());
            resultPage.setPages(doctorPage.getPages());
            return resultPage;

        }
        return new Page<>(pageNum, pageSize);

    }

    @Override
    public List<String> getTitle() {
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT title");
        List<Doctor> doctors = doctorMapper.selectList(wrapper);
        return doctors.stream()
                .map(Doctor::getTitle)
                .collect(Collectors.toList());
    }
}

